package com.example.myapplication.mvvm;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Presentation;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.hardware.display.DisplayManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.example.myapplication.BR;
import com.example.myapplication.R;
import com.example.myapplication.databinding.ActivityMainBinding;
import com.example.myapplication.designmode.factory.Factory;
import com.example.myapplication.designmode.factory.Product;
import com.example.myapplication.designmode.factory.abstractfa.ConcreteFactory;
import com.example.myapplication.designmode.factory.abstractfa.ProductA;
import com.example.myapplication.designmode.factory.abstractfa.ProductB;
import com.example.myapplication.designmode.liabilitylinkmodel.PasswordVerify;
import com.example.myapplication.designmode.liabilitylinkmodel.PhoneVerify;
import com.example.myapplication.designmode.liabilitylinkmodel.UserAccount;
import com.example.myapplication.designmode.liabilitylinkmodel.UserNameVerify;
import com.example.myapplication.designmode.liabilitylinkmodel2.ConcreteHandlerA;
import com.example.myapplication.designmode.liabilitylinkmodel2.ConcreteHandlerB;
import com.example.myapplication.designmode.liabilitylinkmodel2.ConcreteHandlerC;
import com.example.myapplication.designmode.liabilitylinkmodel2.Handler;
import com.example.myapplication.designmode.liabilitylinkmodel2.Request;
import com.example.myapplication.designmode.liabilitylinkmodel2.RequestType;
import com.example.myapplication.designmode.single.BuilderModel;
import com.example.myapplication.mylivedata.LiveDataBus;
import com.example.myapplication.options.GlideApp;
import com.example.myapplication.reflect.Reflect;
import com.example.myapplication.rxjava.RXJava;
import com.example.myapplication.viewmodelsharedcommondata.vd1.ShareViewModelProvider;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {


    /**
     * 于是想，不如利用引用计数来设计一个新的数据共享功能
     * <p>
     * 它应该能提供在多个Activity和Fragment之间都获得同一份共享数据
     * 它应该能在共享数据没人引用时自动清理资源
     * 它应该能在发生销毁重建时保留原来的共享数据实例
     * <p>
     * 对于第一个问题，只要以共享数据实例作为key保存即可
     * <p>
     * 对于第二个问题，可以利用已经现成的Lifecycle来实现引用计数
     * <p>
     * 对于第三个问题，见下面分析
     * ————————————————
     * 版权声明：本文为CSDN博主「hijunmeng」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
     * 原文链接：https://blog.csdn.net/huweijian5/article/details/114575986
     */

    private List<Person> mDatas = new ArrayList<>();
    LiveDataBus liveDataBus;
    private static MMKV mmkv;
    SharedPreferences sharedPreferences;

    @RequiresApi(api = Build.VERSION_CODES.O)
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mBinding.setLifecycleOwner(this);
        TestViewModel viewModel = new ViewModelProvider(this).get(TestViewModel.class);
        viewModel.startTimer();
        mBinding.setVariable(BR.vm, viewModel);

        LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mBinding.rvRecyclerview.setLayoutManager(mLinearLayoutManager);
        mBinding.rvRecyclerview.setItemAnimator(new DefaultItemAnimator());

        String url = "https://cdn.pixabay.com/photo/2023/07/20/06/53/falcon-8138544_1280.jpg";
        GlideApp.with(this)
//                .asBitmap()
                .asDrawable()
                .load(url)
                .applyAvatar(1024 * 3)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                       Bitmap bitmap = resource;
                        return false;
                    }
                })
                .into(mBinding.ivImageView);


        GlideApp.with(this)
                .fade()//  在MyGlideExtension 类里面自定义 fade 方法返回自己想要的类型
                .load(url)
                .applyAvatar(1024 * 3)
                .listener(new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(mBinding.ivImageView);
        getSynchronizationImage(url);
        //  只下载图片，不显示


        sharedPreferences = getSharedPreferences("test", MODE_PRIVATE);
        mmkv = MMKV.defaultMMKV();
        mmkv.encode("1", 1);

        //  构建者模式  使用
        BuilderModel build = new BuilderModel.Builder()
                .setColor("reddd")
                .setHeight(150)
                .setWidth(200).Build();
        liveDataBus = new LiveDataBus().getLiveDataBus();
        liveDataBus.with("msg", String.class, true).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String t) {
                liveDataBus.with("msg", String.class, true).setValue("我来了右面");
            }
        });

        TestViewModel testViewModel = ShareViewModelProvider.get(this, TestViewModel.class);
        testViewModel.onCleared();

//        DisplayManager systemService = getSystemService("1")(DisplayManager);
//        Display[] displays = systemService.getDisplays();
//        Presentation presentation = new Presentation(this);
//

        Reflect.getReflect();

        for (int i = 0; i < 50; i++) {

            List<User> listUser = new ArrayList<>();
            for (int j = 0; j < 5; j++) {
                User user = new User("张三" + j, (25 + j) + "");
                listUser.add(user);
            }
            mDatas.add(new Person("falseName" + i, "laseName" + i, listUser));
        }
        mBinding.rvRecyclerview.setAdapter(new RecyclerAdapter(mDatas, this));


        getLifecycle().addObserver(new TestClass());

        findViewById(R.id.tv_textview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
//                Toast.makeText(MainActivity.this, "计时到第" + viewModel.getTimeCount() + "秒", Toast.LENGTH_SHORT).show();
            }
        });


        LifecycleOwner owner = MainActivity.this;
        viewModel.getTimeCount().observe(owner, integer -> {

//            Toast.makeText(MainActivity.this, "计时到第" + integer + "秒", Toast.LENGTH_SHORT).show();
//            Log.v("G", "timeCount = " + integer);
        });

        setLiablityLinkModel();
        setLiablityLinkModel2();
        setFactory();
    }

    private void setFactory() {
//        使用工厂创建产品
        Product a = Factory.createProduct("A");
        String use = a.getUse();
        Product b = Factory.createProduct("B");
        String use1 = b.getUse();
        String use2 = b.getUse();

        ConcreteFactory factory = new ConcreteFactory();
        ProductA productA1 = factory.createProductA1();
        productA1.useA();
        ProductA productA2 = factory.createProductA2();
        productA2.useA();
        ProductB productB1 = factory.createProductB1();
        productB1.useB();
        ProductB productB2 = factory.createProductB2();
        productB2.useB();
        ProductB productB3 = factory.createProductB2();
    }

    private void setLiablityLinkModel() {

        UserNameVerify userNameVerify = new UserNameVerify();
        PasswordVerify passwordVerify = new PasswordVerify();
        PhoneVerify phoneVerify = new PhoneVerify();
        UserAccount userAccount = new UserAccount();
        userAccount.setUserName("username");
        userAccount.setPassword("123456");
        userAccount.setPhoneNumber("13888888888");
        // 创建职责链
        passwordVerify.setNextVerify(phoneVerify);
        userNameVerify.setNextVerify(passwordVerify);
        // 开始校验 , 执行职责链
        userNameVerify.deploy(userAccount);
    }

    private void setLiablityLinkModel2() {
        Handler handlerA = new ConcreteHandlerA();
        Handler handlerB = new ConcreteHandlerB();
        Handler handlerC = new ConcreteHandlerC();
        handlerA.setSuccessor(handlerB);
        handlerB.setSuccessor(handlerC);


        Request request1 = new Request("已处理 1", RequestType.TYPE_A);
        Request request2 = new Request("已处理 2", RequestType.TYPE_B);
        Request request3 = new Request("已处理 3", RequestType.TYPE_C);

        handlerA.handleRequest(request1);
        handlerB.handleRequest(request2);
        handlerC.handleRequest(request3);
    }

    /**
     * 同步方法获取图片
     *
     * @param url
     */
    private void getSynchronizationImage(String url) {

        FutureTarget<Bitmap> submit = GlideApp.with(this)
                .asBitmap()
//                .asDrawable()
                .load(url)
//                .applyAvatar(1024 * 3)// 设置图片大小
                .submit(150, 150);//注意 applyAvatar 和submit方法不可以同时调用，不用submit方法设置的宽高没有起到作用
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = submit.get();
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        getLifecycle().addObserver(new TestClass());
    }

    public void spOnClick(View view) {
        Log.e("SP", "SP保存数据开始");
        SharedPreferences.Editor edit = sharedPreferences.edit();
        Random random = new Random();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            edit.putLong(String.valueOf(i), random.nextInt()).commit();
        }
        long tiem = System.currentTimeMillis() - start;

        Log.e("SP", "SP保存数据写入耗时  " + tiem + "  ms");
    }

    public void mmkvOnClick(View view) {
        Log.e("MMKV", "MMKV保存数据开始");

        long start = System.currentTimeMillis();
        Random random = new Random();
        for (int i = 0; i < 10000; i++) {
            mmkv.encode(String.valueOf(i), random.nextInt());
        }
        long tiem = System.currentTimeMillis() - start;

        Log.e("MMKV", "MMKV保存数据写入耗时  " + tiem + "  ms");
    }
}